<?php
namespace plugin\ky_black\app\admin\service;

use plugin\ky_black\app\admin\model\User;
use plugin\ky_black\app\admin\model\UserAccount;
use support\Db;

class MemberService
{
    /**
     * 获取会员列表
     */
    public function getList(int $page, int $pageSize, string $keyword = '', string $type = '', string $status = '')
    {
        $query = User::query();
        
        // 搜索条件
        if ($keyword) {
            $query->where(function ($q) use ($keyword) {
                $q->where('name', 'like', "%{$keyword}%")
                  ->orWhere('phone', 'like', "%{$keyword}%")
                  ->orWhere('id_card', 'like', "%{$keyword}%");
            });
        }
        
        if ($type) {
            $query->where('type', $type);
        }
        
        if ($status !== '') {
            $query->where('status', $status);
        }
        
        $total = $query->count();
        $list = $query->offset(($page - 1) * $pageSize)
                     ->limit($pageSize)
                     ->orderBy('created_at', 'desc')
                     ->get();
        
        return [
            'total' => $total,
            'list' => $list
        ];
    }

    /**
     * 创建会员
     */
    public function create(array $data)
    {
        Db::beginTransaction();
        try {
            // 创建用户基本信息
            $user = new User();
            $user->type = $data['type'];
            $user->name = $data['name'] ?? null;
            $user->phone = $data['phone'];
            $user->id_card = $data['id_card'] ?? null;
            $user->gender = $data['gender'] ?? 'unknown';
            $user->email = $data['email'] ?? null;
            
            if ($data['type'] === 'organization') {
                $user->company_name = $data['company_name'];
                $user->business_license = $data['business_license'];
                $user->legal_representative = $data['legal_representative'];
                $user->company_address = $data['company_address'];
                $user->contact_phone = $data['contact_phone'];
                $user->company_email = $data['company_email'] ?? null;
            }
            
            $user->save();

            // 创建登录账号
            $account = new UserAccount();
            $account->user_id = $user->user_id;
            $account->username = $data['username'];
            $account->salt = $this->generateSalt();
            $account->password = $this->encryptPassword($data['password'], $account->salt);
            $account->save();

            Db::commit();
            return $user;
        } catch (\Exception $e) {
            Db::rollBack();
            throw $e;
        }
    }

    /**
     * 更新会员信息
     */
    public function update(int $userId, array $data)
    {
        $user = User::findOrFail($userId);
        
        Db::beginTransaction();
        try {
            // 更新基本信息
            $user->name = $data['name'] ?? $user->name;
            $user->phone = $data['phone'] ?? $user->phone;
            $user->email = $data['email'] ?? $user->email;
            
            if ($user->type === 'organization') {
                $user->company_name = $data['company_name'] ?? $user->company_name;
                $user->business_license = $data['business_license'] ?? $user->business_license;
                $user->legal_representative = $data['legal_representative'] ?? $user->legal_representative;
                $user->company_address = $data['company_address'] ?? $user->company_address;
                $user->contact_phone = $data['contact_phone'] ?? $user->contact_phone;
                $user->company_email = $data['company_email'] ?? $user->company_email;
            }
            
            $user->save();

            // 如果需要修改密码
            if (!empty($data['password'])) {
                $account = UserAccount::where('user_id', $userId)->first();
                $account->password = $this->encryptPassword($data['password'], $account->salt);
                $account->save();
            }

            Db::commit();
            return $user;
        } catch (\Exception $e) {
            Db::rollBack();
            throw $e;
        }
    }

    /**
     * 获取会员详情
     */
    public function getDetail(int $userId)
    {
        $user = User::with('account')->findOrFail($userId);
        return $user;
    }

    /**
     * 修改会员状态
     */
    public function changeStatus(int $userId, int $status)
    {
        $user = User::findOrFail($userId);
        $user->status = $status;
        $user->save();
        
        // 同步更新账号状态
        UserAccount::where('user_id', $userId)->update(['status' => $status]);
        
        return true;
    }

    /**
     * 重置密码
     */
    public function resetPassword(int $userId)
    {
        $account = UserAccount::where('user_id', $userId)->firstOrFail();
        
        // 生成新密码
        $newPassword = $this->generateRandomPassword();
        $account->password = $this->encryptPassword($newPassword, $account->salt);
        $account->save();
        
        return $newPassword;
    }

    /**
     * 生成密码盐值
     */
    protected function generateSalt(int $length = 16): string
    {
        return bin2hex(random_bytes($length));
    }

    /**
     * 加密密码
     */
    protected function encryptPassword(string $password, string $salt): string
    {
        return hash('sha256', $password . $salt);
    }

    /**
     * 生成随机密码
     */
    protected function generateRandomPassword(int $length = 8): string
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()';
        $password = '';
        
        for ($i = 0; $i < $length; $i++) {
            $password .= $chars[random_int(0, strlen($chars) - 1)];
        }
        
        return $password;
    }
} 